package com.animerank.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.animerank.entity.User;
import com.animerank.service.IUserService;
import com.animerank.mapper.UserMapper;
import com.animerank.dto.UserRegisterDTO;
import com.animerank.dto.UserLoginDTO;
import com.animerank.dto.Result;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.Cookie;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import cn.dev33.satoken.stp.StpUtil;
import java.time.LocalDateTime;

/**
 * 用户服务实现类
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public Result<?> register(UserRegisterDTO userRegisterDTO) {
        // 检查用户名是否已存在
        User existingUser = userMapper.selectByUsername(userRegisterDTO.getUsername());
        if (existingUser != null) {
            return Result.fail("用户名已存在");
        }

        // 创建新用户
        User user = new User();
        user.setUsername(userRegisterDTO.getUsername());
        user.setPasswordHash(passwordEncoder.encode(userRegisterDTO.getPassword()));
        user.setEmail(userRegisterDTO.getEmail());
        user.setCreatedAt(LocalDateTime.now());

        // 保存用户
        userMapper.insert(user);
        return Result.success("注册成功");
    }

    @Override
    public Result<?> login(UserLoginDTO userLoginDTO, HttpServletResponse response) {
        // 查询用户
        User user = userMapper.selectByUsername(userLoginDTO.getUsername());
        if (user == null) {
            return Result.fail("用户名或密码错误");
        }

        // 验证密码
        if (!passwordEncoder.matches(userLoginDTO.getPassword(), user.getPasswordHash())) {
            return Result.fail("用户名或密码错误");
        }

        // 更新最后登录时间
        user.setLastLogin(LocalDateTime.now());
        userMapper.updateById(user);

        // 登录并生成token
        StpUtil.login(user.getId());
        String token = StpUtil.getTokenValue();
        
        // 设置响应头
        response.setHeader("Authorization", token);
       
        return Result.success(token);
    }

    @Override
    public Result<User> getCurrentUser() {
        // 检查是否登录
        if (!StpUtil.isLogin()) {
            return Result.fail(401, "请先登录");
        }

        // 获取当前登录用户ID
        Long userId = StpUtil.getLoginIdAsLong();
        User user = userMapper.selectById(userId);

        // 如果用户不存在，返回错误信息
        if (user == null) {
            return Result.fail(404, "用户不存在");
        }

        // 隐藏密码信息
        user.setPasswordHash(null);

        return Result.success(user);
    }

    @Override
    public Result<?> logout() {
        // 登出
        StpUtil.logout();
        return Result.success("登出成功");
    }

}